//首先获取个人信息头部的模板
(function() {
	$.validator.addMethod("passwordVaild",function(value,element){
	    var score = /^(?!(?:\d+|[a-zA-Z]+)$)[\da-zA-Z]*$/;
	    return this.optional(element) || (score.test(value));
	},"<span class='text-danger'>密码需要包含字母和数字</span>");

	// 为侧边栏添加点击按钮的一些事件；
	$('.sidenav .list-group-item').click(function() {
		$(this).addClass('active').siblings().removeClass('active');
		var arr = ['.myCourses', '.BaseInformation', '.uploadImg','.fixpwd'];
		var id = $(this).attr('showLayer');
		for (var i = 0; i < arr.length; i++) {
			$(arr[i]).css({
				'display' : "none"
			})
		}
		$('.' + id).css({
			'display' : 'block'
		})
	});
	
	//初始化日期选择控件
	$('.form_date').datetimepicker({
        language:  'zh-CN',
        weekStart: 1,
        todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		minView: 2,
		forceParse: 0
    });
	
	//用户基本信息验证
	$("#user-profile-form").validate({
	      errorClass: "text-danger",
	      onkeyup: false,
	      errorPlacement: function(error, element) {
	          $( element ).closest(".controls").find(".help-block").append(error);
	      },
	      errorElement: "span"
	  });
	//修改密码验证
	$("#settings-password-form").validate({
	      errorClass: "text-danger",
	      onkeyup: false,
	      errorPlacement: function(error, element) {
	          $( element ).closest(".controls").find(".help-block").append(error);
	      },
	      errorElement: "span"
	  });
	//身份证校验
	$.validator.addMethod("cardValidator", function(value, element) {
	    return this.optional(element) || isIdCardNo(value);
	},"请输入正确的身份证号");
	//手机号校验
	$.validator.addMethod("mobileValidator",function(value,element){
	      var pattern = /^1[34578]\d{9}$/; 
    	  var result = this.optional(element) || (pattern.test(value));
	      return result;
	  },"请输入正确的手机号");
	//用户当前密码校验
	$.validator.addMethod("currentPwdValidator",function(value,element){
		var response = $.ajax({
			url: '../../portal/open/getCurrentUser.json',
			type: 'POST',
			dataType: 'json',
			async:false
		}).responseText;
		var serverPwd = $.parseJSON(response).data.user.password;
		var result = this.optional(element) || (serverPwd==$.md5(value));
		return result;
	},"您输入的密码不正确");

	//表单提交
	//更新用户基本信息
	$("#profile-save-btn").click(function(){
		if(!$('#user-profile-form').valid()){
			  return;
		  }
		
		var $form = $(this).closest("form");
		$.ajax({
			url: '../userinfo/updateUserInfo.json?_t='+$.now(),
			type: 'POST',
			dataType: 'json',
			data: $form.serialize(),
		})
		.done(function(data) {
			if(data.success){
				$form.find(".alert").text("基础信息保存成功。").addClass("alert-success").show();
			}else{
				$form.find(".alert").text("基础信息保存失败，请稍后再试。").addClass("alert-error").show();
			}
		})
		.fail(function(data) {
			$form.find(".alert").text("基础信息保存失败，请联系管理员。").addClass("alert-error").show();
		});
	});
	//更新用户密码
	$("#password-save-btn").click(function(){
		if(!$('#settings-password-form').valid()){
			  return;
		  }
		var $form = $(this).closest("form");
		$.ajax({
			url: '../userinfo/updateUserPwd.json?_t='+$.now(),
			type: 'POST',
			dataType: 'json',
			data: {"password":$.md5($.trim($("#form_newPassword").val()))},
			async:false
		})
		.done(function(data) {
			if(data.success){
				$form.find(".alert").text("密码修改成功。").addClass("alert-success").show();
//				$form.find("#form_newPassword").val("");
//				$form.find("#form_confirmPassword").val("");
//				$form.find("#form_currentPassword").val("");
				window.location.reload();
			}else{
				$form.find(".alert").text("密码修改失败，请稍后再试。").addClass("alert-error").show();
			}
		})
		.fail(function(data) {
			$form.find(".alert").text("密码修改失败，请联系管理员。").addClass("alert-error").show();
		});
	});
	
})()
$(function(){
//我的课程
var learned=null;//学过对象集合
var learning=null;//未学完对象集合
var page = 1;//初始化页码
var pagesize=3;
var learnState=1;
	//个人信息头部
	$.ajax({
		type:"get",
		url:"../../opwguser/usertarget/findCurrentTarget.json",
		async:true,
		success:function(data){
			if(data.data.accountBean.headPhoto){
				data.data.accountBean.headPhoto="../../components/gtattachment/open/downloadAttachment.json?attachmentId="+data.data.accountBean.headPhoto;
			}
			else{
				data.data.accountBean.headPhoto="../../images/klxlearning/man.png";
			}
			if(data.data.userTargetList&&data.data.userTargetList.length){

				data.data.userTargetList[0].targetConfigBean.targetBeginTime=formatTime(data.data.userTargetList[0].targetConfigBean.targetBeginTime, 'yyyy/MM/dd HH:mm:ss'); 
				data.data.userTargetList[0].targetConfigBean.targetEndTime=  formatTime(data.data.userTargetList[0].targetConfigBean.targetEndTime, 'yyyy/MM/dd HH:mm:ss');
				if(!data.data.userTargetList[0].currentTotalTime){
					data.data.userTargetList[0].currentTotalTime = 0;
				}
				if(!data.data.userTargetList[0].currentTotalScore){
					data.data.userTargetList[0].currentTotalScore = 0;
				}
				var timeRatio=parseInt((data.data.userTargetList[0].currentTotalTime/data.data.userTargetList[0].targetConfigBean.targetTotalTime)*100);
				data.data.userTargetList[0].timeRatio=timeRatio>100?100:timeRatio;
				var scoreRatio=parseInt((data.data.userTargetList[0].currentTotalScore/data.data.userTargetList[0].targetConfigBean.targetTotalScore)*100);
				data.data.userTargetList[0].scoreRatio=scoreRatio>100?100:scoreRatio;
				var userSpaceTopTpl=_.template($("#userSpaceTopTpl").html());
				var userSpaceTopHtml=userSpaceTopTpl(data.data);
				$("#userSpaceTop").html(userSpaceTopHtml);
			}
			else{
				var userSpaceTopTpl=_.template($("#userSpaceTopNoneTpl").html());
				var userSpaceTopHtml=userSpaceTopTpl(data.data);
				$("#userSpaceTop").html(userSpaceTopHtml);
			}
			
		}
	});
	
	function formatTime(time, format){
		var t = new Date(time);
		  var tf = function(i) {
		    return(i < 10 ? '0' : '') + i
		  };
		  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
		    switch(a) {
		      case 'yyyy':
		        return tf(t.getFullYear());
		        break;
		      case 'MM':
		        return tf(t.getMonth() + 1);
		        break;
		      case 'mm':
		        return tf(t.getMinutes());
		        break;
		      case 'dd':
		        return tf(t.getDate());
		        break;
		      case 'HH':
		        return tf(t.getHours());
		        break;
		      case 'ss':
		        return tf(t.getSeconds());
		        break;
		    }
		  });
	}
	
	function getUseCoures2(fn){
//	if(!learning){
		$.ajax({
			type:"get",
			url:"../../portal/courselibrary/findLearninfoUser.json?queryCourseCheckState=2&pageSize="+pagesize+"&currentPage="+page,//未学完
			async:true,
			success:function(data){
				if(data.success&&data.data.resultList.length){
				//取出所有时间并对对象分组
				for(var i=0;i<data.data.resultList.length;i++){
					console.log(data.data.resultList.length)
						var learningtime = parseInt(data.data.resultList[i].courseTime/60);//秒转为分钟
						data.data.resultList[i].courseTime=learningtime;
						var learntime=data.data.resultList[i].course.courseTime;
						var ratio=parseInt((learningtime/learntime)*100);//计算学习百分比
						if(ratio>100){
							ratio=100;
						}
						data.data.resultList[i].ratio=ratio;
						learning=data.data;
			    }
	            //生成学习中模板函数，填充数据，写入html
				var useTpl=_.template($("#useTpl").html());
				var learningHtml=useTpl(learning);
				console.log()
				$("#learning").html(learningHtml);
				var maxPage=learning.maxPage;
				if(fn)(fn(maxPage));
				}
			}
		});
//	  }
//	  else{
//	  	//生成学习中模板函数，填充数据，写入html	
//		var useTpl=_.template($("#useTpl").html());
//		var learningHtml=useTpl(learning);
//		$("#learning").html(learningHtml);
//		var maxPage=learning.maxPage;
//		if(fn)(fn(maxPage)); 
//	  }
	}
	function getUseCoures1(fn){
//	if(!learned){
		$.ajax({
			type:"get",
			url:"../../portal/courselibrary/findLearninfoUser.json?queryCourseCheckState=1&pageSize="+pagesize+"&currentPage="+page,//学完
			async:true,
			success:function(data){
				if(data.success&&data.data.resultList.length){
				//取出所有时间并对对象分组
				for(var i=0;i<data.data.resultList.length;i++){
					console.log(data.data.resultList.length)
						var learningtime = parseInt(data.data.resultList[i].courseTime/60);//秒转为分钟
						data.data.resultList[i].courseTime=learningtime;
						var learntime=data.data.resultList[i].course.courseTime;
						var ratio=parseInt((learningtime/learntime)*100);//计算学习百分比
						if(ratio>100){
							ratio=100;
						}
						data.data.resultList[i].ratio=ratio;
						learned=data.data;
			    }
	            //生成学习中模板函数，填充数据，写入html
				var useTpl=_.template($("#useTpl").html());
				var learnedHtml=useTpl(learned);
				$("#learned").html(learnedHtml);
				var maxPage=learned.maxPage;
				if(fn)(fn(maxPage));
				}
			}
		});
//	  }
//	  else{
//	  	//生成学习中模板函数，填充数据，写入html
//		var useTpl=_.template($("#useTpl").html());
//		var learnedHtml=useTpl(learned);
//		$("#learned").html(learnedHtml);
//		var maxPage=learned.maxPage;
//		if(fn)(fn(maxPage));
//	  }
	}
	getUseCoures2(pageComponents);
	function pageComponents(maxPage){
	  var maxPage = maxPage;
	  //将翻页组件插入进来
	  var components = new PageNum(maxPage);
	  //为翻页添加事件；
	  components.events(function(num){
		      page = num;
			  getUseCoures2();
	  })
	}
	$("#learnedBtn").click(function(){
		learnState=1;
		getUseCoures1(pageComponents);
		function pageComponents(maxPage){
			  var maxPage = maxPage;
			  //将翻页组件插入进来
			  var components = new PageNum(maxPage);
			  //为翻页添加事件；
			  components.events(function(num){
				      page = num;
					  getUseCoures1();
			  })
		}
	})
	$("#learningBtn").click(function(){
		learnState=2;
		getUseCoures2(pageComponents);
		function pageComponents(maxPage){
			  var maxPage = maxPage;
			  //将翻页组件插入进来
			  var components = new PageNum(maxPage);
			  //为翻页添加事件；
			  components.events(function(num){
				      page = num;
					  getUseCoures2();
			  })
		}
	})

});